package blog.util;

public final class StringUtils {
	public static String null2empty( String source )
	{
		if ( source==null )
			return "";
		else
			return source;
	}
	
	private static final String PARAM1 = "{%1}";
	private static final String PARAM2 = "{%2}";
	public static String combin( String srcBody, String param1 )
	{
		int index = srcBody.indexOf( PARAM1 );
		if ( index==-1 )
		{
			return srcBody;
		}
		else
		{
			StringBuffer buffer = new StringBuffer( srcBody.length()+param1.length() );
			buffer.append( srcBody.substring( 0, index ) );
			buffer.append( param1 );
			buffer.append( srcBody.substring( index+PARAM1.length() ) );
			return buffer.toString();
		}
	}
	
	public static String combin( String srcBody, String param1, String param2 )
	{
		srcBody = combin(srcBody, param1);
		int index = srcBody.indexOf( PARAM2 );
		if ( index==-1 )
		{
			return srcBody;
		}
		else
		{
			StringBuffer buffer = new StringBuffer( srcBody.length()+param1.length() );
			buffer.append( srcBody.substring( 0, index ) );
			buffer.append( param2 );
			buffer.append( srcBody.substring( index+PARAM2.length() ) );
			return buffer.toString();
		}
	}

	public static String combin( String srcBody, String[] params )
	{
		if ( params!=null || params.length>0 )
		{
			StringBuffer buffer = new StringBuffer( srcBody.length() + params.length*20 ); //pre-length;
			String searchFlag;
			int searchResult;
			for ( int i=0; i<params.length; i++ )
			{
				searchFlag = "{%"+ (i+1) +"}";
				searchResult = srcBody.indexOf( searchFlag );
				if ( searchResult==-1 )
				{
					continue;
				}
				buffer.delete( 0, buffer.length() );
				buffer.append( srcBody.substring( 0, searchResult ) );
				buffer.append( params[i] );
				buffer.append( srcBody.substring( searchResult + searchFlag.length() ) );
				srcBody = buffer.toString();
			}
		}
		return srcBody;
	}
}
